import {Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams} from 'ionic-angular';
import {LoadingService} from "../../../services/common/loading.service";
import {ToastService} from "../../../services/common/toast.service";
import {PageInfoModel} from "../../../model/common/page-info.model";
import {TeamTeamIncreaseProvider} from '../../../providers/my-team/team-team-increase/team-team-increase.provider';
import {MessageBushService} from "../../../services/common/message-bush.service";
import * as moment from 'moment';
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {EndlessListComponent} from "../../../components/common/endless-list/endless-list";
import {AdpActionSheetController} from '../../../components/common/adp-action-sheet/adp-action-sheet-controller';
import {DateService} from "../../../services/common/date.service";

@IonicPage()
@Component({
    selector: 'page-team-team-increase',
    templateUrl: 'team-team-increase.html',
    providers: [
        TeamTeamIncreaseProvider,
        LoadingService,
        ToastService,
        DateService
    ]
})
export class TeamTeamIncreasePage extends InfiniteScrollModel {
    //全部业务组
    public groupList: Array<any> = [];
    //业务组信息
    public groupRecruitTarget: any = {};
    //当前显示的数据
    public currentScreenData: any = [];
    //切换个人增员与团队增员
    public overView: string = '';
    //营销员等级
    public agentLevel: string = <string>localStorage.getItem('agentLevel');
    //显示返回按钮
    public showBackBtn: boolean = false;
    //分页样式
    public listStyle: any = {};
    //加载监听
    public isLoaded: boolean = false;
    //全部个人增员数据
    public personIncrease: any = {};
    //人才库总人数
    public totalTalentNumber: number = 0;
    //个人增员请求参数
    public filter = {
        starttime: moment(new Date()).format('YYYY') + '-01',
        endtime: moment(new Date()).format('YYYY-MM')
    };
    //中间缓存时间 --个人增员
    public personIncreaseDate = {
        starttime: moment(new Date()).format('YYYY') + '-01',
        endtime: moment(new Date()).format('YYYY-MM')
    };
    //中间缓存时间 --团队增员
    public teamIncreaseDate = {
        starttime: moment(new Date()).format('YYYY-MM') + '-01',
        endtime: moment(new Date()).format('YYYY-MM')
    };
    //是否是第一次加载
    public personIncreaseReady: boolean = false;
    public totalMemberReady: boolean = false;
    // 时间插件--年月日汉字填充
    public pickerOptions = {
        cssClass: 'filter-add-picker'
    };
    //个人增员 -- 时间范围验证
    public personTimeError: boolean = false;
    //团队增员 -- 时间范围验证
    public teamTimeError: boolean = false;
    //时间范围
    public yearList: Array<any>;

    @ViewChild('endlessList') endlessList: EndlessListComponent;
    @ViewChild(Content) content: Content;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                private load: LoadingService,
                private toast: ToastService,
                private teamIncreaseProvider: TeamTeamIncreaseProvider,
                private actionSheetCtrl: AdpActionSheetController,
                public dateService: DateService,) {
        super();
        //初始化参数 -- 团队增员
        this.pageParams.pageSize = 10;
        this.pageParams.pageNum = 1;
        this.pageParams.condition = {
            name: '',
            groupId: '',
            starttime: moment(new Date()).format('YYYY-MM') + '-01',
            endtime: moment(new Date()).format('YYYY-MM')
        };
        this.navCtrl.swipeBackEnabled = false;
        //初始化时间范围
        this.yearList = this.dateService.getYearList(1900);
    }

    ionViewDidLoad() {
        //判断从哪里进入
        this.overView = this.navParams.get('overView');
        //显示返回按钮
        this.showBackBtn = this.overView === '1';
        if (!this.navParams.get('isLoading')) {
            //初始化数据
            this.toggleView(this.overView);
        }
        //初始化布局
        this.layoutInit();
    }

    ionViewDidEnter() {//监听候选人变化
        // console.log('ionViewDidEnter')
        let upDateCode = MessageBushService.getMessage(MessageBushService.keys.teamTeamIncreaseUpdate);
        if (upDateCode === '1') {
            this.getPersonIncrease(true);
            MessageBushService.setMessage(MessageBushService.keys.teamTeamIncreaseUpdate, '0');
        }
    }

    // ionViewWillEnter() { console.log('ionViewWillEnter') }
    // ionViewWillLeave() { console.log('ionViewWillLeave') }
    // ionViewDidLeava() { console.log('ionViewDidLeava') }
    // ionViewCanEnter() { console.log('ionViewCanEnter') }
    // ionViewCanLeave() { console.log('ionViewCanLeave') }
    // ionViewWillUnload() { console.log('ionViewWillUnload') }


    // ngOnDestroy() { console.log('ngOnDestroy') }  /*组件注销时的清理工作，通常用于移除事件监听，退订可观察对象等*/
    // ngAfterViewChecked() { console.log('ngAfterViewChecked') }  /*视图发生变化检测之后，这个可以用来保证用户视图的及时更新*/
    // ngAfterViewInit() { console.log('ngAfterViewInit') }  /*视图 初始化之后*/
    // ngAfterContentChecked() { console.log('ngAfterContentChecked') }  /*内容变更检测之后*/
    // ngAfterContentInit() { console.log('ngAfterContentInit') }  /*内容初始化到组件之后*/
    // ngDoCheck() { console.log('ngDoCheck') }  /*手动触发更新检查*/
    // ngOnInit() { console.log('ngOnInit') }  /*组件初始化，通常会设置一些初始值*/
    // ngOnChanges() { console.log('ngOnChanges') } /*检测到输入数据变化，首次触发发生在ngOnInit前。注意对象的属性发生变化时监听不到*/

    /**
     * 时间查询
     */
    dateSearch(type: string): void {
        if (type === 'getPersonIncrease') {//个人增员
            this.filter.starttime = this.personIncreaseDate.starttime
            this.filter.endtime = this.personIncreaseDate.endtime;
        } else {//团队增员
            this.pageParams.condition.starttime = this.teamIncreaseDate.starttime;
            this.pageParams.condition.endtime = this.teamIncreaseDate.endtime;
        }
        this[type]();
    }

    /**
     * 筛选时间 -- 验证
     */
    dataValidate() {
        //团队增员 -- 时间范围
        if (moment(this.teamIncreaseDate.starttime).unix() > moment(this.teamIncreaseDate.endtime).unix()) {
            this.teamTimeError = true;
        } else {
            this.teamTimeError = false;
        }
        //个人增员 -- 时间范围
        if (moment(this.personIncreaseDate.starttime).unix() > moment(this.personIncreaseDate.endtime).unix()) {
            this.personTimeError = true;
        } else {
            this.personTimeError = false;
        }
    }

    /**
     * 跳转 TalentPoolPage
     */
    goDetail(process) {
        if (typeof process === 'undefined') {
            this.navCtrl.push('TalentPoolPage');
        } else {
            this.navCtrl.push('TalentPoolPage', {
                processStartTime: this.filter.starttime,
                processEndTime: this.filter.endtime,
                process
            });
        }

    }

    /**
     * 获取个人增员 or 获取团队增员
     */
    toggleView(str: any) {
        this.overView = str;
        if (!this.totalMemberReady && str === '1' || !this.personIncreaseReady && str !== '1')
            this.overView !== '1' ? this.getPersonIncrease() : this.getTotalMember();
    }

    /**
     * 获取个人增员 -- 人才库总数
     */
    getTotalTalent(cb?) {
        this.teamIncreaseProvider.getTotalTalent().subscribe(data => {
            this.totalTalentNumber = data;
            if(cb)cb();
        }, () => {
            if(cb)cb();
        });
    }

    /**
     * 获取个人增员  -- 增员统计
     */
    getPersonIncrease(onlyGetTotal?: boolean,cb?) {
        this.isLoaded = false;
        this.load.showLoading();
        if (onlyGetTotal || !this.personIncreaseReady) this.getTotalTalent(cb); //初始化一次，人才库总数
        this.teamIncreaseProvider.getPersonIncrease(this.filter).subscribe(data => {
            if(cb)cb();
            this.isLoaded = true;
            this.personIncrease = data;
            this.personIncreaseReady = true;
            this.load.dismissLoading();
        }, () => {
            if(cb)cb();
            this.isLoaded = true;
            this.load.dismissLoading();
        });
    }

    /**
     * 获取团队增员
     */
    getTotalMember() {
        if (!this.isLoaded && this.totalMemberReady) {
            this.toast.showToast('数据正在加载中...');
            return;
        };
        this.isLoaded = false;
        this.load.showLoading();
        this.pageParams.pageNum = 1;
        this.teamIncreaseProvider.getTotalMember(this.pageParams).subscribe(pageData => {
            this.pageInfo = pageData.pageInfo;
            if (!this.totalMemberReady) this.groupList = pageData.groupList;  //初始化一次,组列表
            this.groupRecruitTarget = pageData.groupRecruitTarget;
            this.currentScreenData = this.pageInfo.list;
            this.isLoaded = true;
            this.endlessList.isArriveBottom = false;
            this.totalMemberReady = true;
            this.load.dismissLoading();
        }, () => {
            this.isLoaded = true;
            this.totalMemberReady = true;
            this.load.dismissLoading();
        });
    }

    /**
     * 团队增员 --选组
     */
    showBusinessGroup(event) {
        if (!this.isLoaded) {
            this.toast.showToast('数据正在加载中...');
            return;
        };
        let temGroup = [];
        this.groupList.forEach((item) => {
            temGroup.push({
                cssClass: item.unitCode === this.pageParams.condition.groupId ? 'action-sheet-selected' : '',
                text: item.unitName,
                handler: () => {
                    this.pageParams.condition.name = item.unitName;
                    this.pageParams.condition.groupId = item.unitCode;
                    this.getTotalMember();
                }
            })
        });
        temGroup.push({
            text: '所有组',
            cssClass: this.pageParams.condition.groupId === '' ? 'action-sheet-selected' : '',
            handler: () => {
                this.pageParams.condition.name = '';
                this.pageParams.condition.groupId = '';
                this.getTotalMember();
            }
        });
        this.actionSheetCtrl.create({
            title: '所辖组',
            cssClass: 'roster-action',
            buttons: temGroup
        }).present();
        event.stopPropagation();
    }

    /**
     * 元素高度
     */
    vw(v: number) {
        return window.innerWidth * v / 100;
    }

    /**
     * 计算列表框高度
     */
    layoutInit() {
        const listHeight = window.innerHeight - this.vw(17.6) - this.vw(45.717) - this.vw(14);
        this.listStyle.height = `${listHeight}px`;
    }

    /**
     * 滑动事件
     */
    scrolling(e) {
        // console.log(e);
    }

    /**
     * 到底事件
     */
    scrollToBottom() {
        const pageTotal = Math.ceil(this.pageInfo.total / this.pageInfo.pageSize);
        if (!this.isLoaded || this.pageParams.pageNum >= pageTotal) {
            this.endlessList.isArriveBottom = this.pageParams.pageNum >= pageTotal ? true : false;
            return;
        }
        this.isLoaded = false;
        this.endlessList.isLoadingData = true;
        this.pageParams.pageNum++;
        this.teamIncreaseProvider.getTotalMember(this.pageParams, null).subscribe(pageData => {
            this.pageInfo = pageData.pageInfo as PageInfoModel;
            this.currentScreenData = this.currentScreenData.concat(this.pageInfo.list);
            this.endlessList.isLoadingData = false;
            this.isLoaded = true;
        },() => {
            this.isLoaded = true;
        });
    }

    /**
     * 返回
     */
    backToProPage() {
        this.navCtrl.pop(null);
    }

    /**
     * 下拉刷新
     */
    doRefresh(refresher) {
        this.getPersonIncrease(true,() => {
            refresher.complete();
        })
    }
}
